package com.stealtime.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;

import java.util.Base64;

public class Img2Base64Utils {
	// 图片转化成base64字符串
	public static String getImageBase64(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
 			in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		// 对字节数组Base64编码
		return Base64.getEncoder().encodeToString(data);// 返回Base64编码过的字节数组字符串
	}

	// 输入流转化成base64字符串
	public static String GetImageStr(InputStream in) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		// String imgFile = "C:/Users/Star/Desktop/test.png";// 待处理的图片
		byte[] data = null;
		// 读取图片字节数组
		try {
			// in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		// 对字节数组Base64编码
		return Base64.getEncoder().encodeToString(data);// 返回Base64编码过的字节数组字符串
	}
	
	public static String changeImageToBase64(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			URL url = new URL(imgFile);
			in = url.openStream();
	        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
	        byte[] buff = new byte[1024];  
	        int rc = 0;  
	        while ((rc = in.read(buff, 0, 1024)) > 0) {  
	            swapStream.write(buff, 0, rc);  
	        }  
	        data = swapStream.toByteArray();  

			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		// 对字节数组Base64编码
		return Base64.getEncoder().encodeToString(data);// 返回Base64编码过的字节数组字符串
	}
}